package com.foo.demo.web.servlet;

import com.foo.demo.dao.model.User;
import com.foo.demo.service.IUserService;
import com.foo.demo.service.impl.UserServiceImpl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Random;

@WebServlet(name = "userServlet", value = "/userServlet")
public class UserServlet extends HttpServlet {

    private static Logger logger = LogManager.getLogger();

    private IUserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.info("doGet");

        String username = req.getParameter("username");
        if (null == username || username.trim().length() < 1) {

            List<User> users = userService.queryAllUser();

            req.setAttribute("userList", users);

            req.getRequestDispatcher("/pages/users.jsp").forward(req, resp);
        } else {
            User user = userService.queryUserByUsername(username);
            req.setAttribute("user", user);
            req.getRequestDispatcher("/pages/user.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.info("doPost");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Random random = new Random(100);
        char[] arr = new char[8];
        for (int i = 0; i < 8; i ++) {
            arr[i] = (char)(random.nextInt() + 48);
        }


        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickName(String.valueOf(arr));
        int i = userService.addUser(user);

        if (i > 0) {
            req.setAttribute("msg", "add user success");
        } else {
            req.setAttribute("msg", "add user failed");
        }
        req.getRequestDispatcher("/userServlet").forward(req, resp);
    }
}
